function return_tag(selector_type, selector_name, html_tag, type, closing_tag) {
	var html = "<" + html_tag + " " + selector_type + "= " + selector_name + ">";
	return ( (typeof closing_tag == 'undefined') ? html : html + "</" + html_tag + ">" );	
}

function return_form(selector_type, selector_name, method, action, closing_tag) {
	html_tag = "form";	
	var html = '<form ' + selector_type + '="' + selector_name + '" action="' + action + '" method="' + method + '">';
                        
	return ( (typeof closing_tag !== 'undefined') ? html : html + "</" + form + ">" );	
}

jQuery("#create_test").submit( function() {	

	$.ajax( {
		url		: 		"ajaxify.php",
		type	: 		"POST",
		data	: 		jQuery(this).serialize(),
		dataType:		"text",		
	}).done(function(response) {		
			var s = jQuery.parseJSON(response);
			if ( s.success === "yes" )  {
				$("#output").html(s[0]);
			}
			
			if ( s.errors === "yes" )  {
				$("#output").html(s[0]);
			}
			
			return false;
	})
	
	return false;
});


$("#popout_aq").click(function() {
	$("#modal_popup").css("display", ( $("#modal_popup").css("display") == "none" ? "block":"none") );
});



$("#cancel").click(function() {
	$("#modal_popup").css("display", "none");
});

$("#insert_questions").click(function() {
	var html = "";
	if ( $("#add_q_mul_choice").attr("checked") == "checked" ) {
		html = '<div class="q_mul_choice question" q_mul_choice="1"><input type="text" class="q_title clearpix" name="q_title" placeholder="What is the title of your question?"><input type="hidden" name="question_type" value="multiple_choice"><textarea name="ans_opt" placeholder="Answer option" class="mul_choice_ans_opt" class="mul_choice_ans_opt"></textarea> <input type="checkbox" title="Mark this as right answer" name="right_ans" class="right_ans"> <a href="#" class="delete_ans_option" title="Delete this answer option">Delete</a> <textarea name="ans_opt" placeholder="Answer option" class="mul_choice_ans_opt"></textarea> <input type="checkbox" title="Mark this as right answer" name="right_ans" class="right_ans"> <a href="#" class="delete_ans_option" title="Delete this answer option">Delete</a> <a href="#" class="insert_mul_choice_answer_option">Insert Answer Option<a></div>';		
		
		// We append the new div in ia.
		$(".ia").append(html);
		
	}
	html = "";
	if ( $("#add_q_match_following").attr("checked") == "checked" ) {
		var html='<div class="q_match_following question clearpix" q_match_following="1"><input type="text" class="q_title clearpix" name="q_title" placeholder="Question type: Match the following. What is the question about?">	<div class="mapping"><div><a href="" class="del_mapping">Delete Mapping</a></div>						<div class="left_column"><textarea type="text" class="left_option" placeholder="Left column option"></textarea> </div>	<div class="right_column"><textarea type="text" class="right_option" placeholder="Matching right column option"></textarea>	</div>		</div>		<div class="mapping"><div><a href="" class="del_mapping">Delete Mapping</a></div><div class="left_column"><textarea type="text" class="left_option" placeholder="Left column option"></textarea> </div>	<div class="right_column"><textarea type="text" class="right_option" placeholder="Matching right column option"></textarea>	</div></div><div class="mapping"><div><a href="" class="del_mapping">Delete Mapping</a></div><div class="left_column"><textarea type="text" class="left_option" placeholder="Left column option"></textarea> </div>	<div class="right_column"><textarea type="text" class="right_option" placeholder="Matching right column option"></textarea>	</div>	</div>		<div class="mapping"><div><a href="" class="del_mapping">Delete Mapping</a></div><div class="left_column"><textarea type="text" class="left_option" placeholder="Left column option"></textarea> </div>	<div class="right_column"><textarea type="text" class="right_option" placeholder="Matching right column option"></textarea>	</div>	</div>	<a href="#" class="insert_match_following_answer_option">Add Another Match<a></div>';
		
		$(".ia").append(html);
	}
	$("#submit_questions").css("display", "block");
});		

jQuery("body").on("click", ".insert_match_following_answer_option", function() {
	$('<div class="mapping"><div><a href="" class="del_mapping">Delete Mapping</a></div> <div class="left_column"><textarea type="text" class="left_option" placeholder="Left column option"></textarea> </div><div class="right_column"><textarea type="text" class="right_option" placeholder="Matching right column option"></textarea></div>').insertBefore(this);
});

jQuery("body").on("click", ".insert_mul_choice_answer_option", function() {
	$('<textarea name="ans_opt" placeholder="Answer option" class="mul_choice_ans_opt"></textarea> <input type="checkbox" title="Mark this as right answer" name="right_ans" class="right_ans"> <a href="#" class="delete_ans_option" title="Delete this answer option">Delete</a><br>').insertBefore(this);
});

jQuery("body").on("click", ".delete_ans_option", function() {
	$(this).prev().remove();
	$(this).prev().remove();
	$(this).remove();
	// TODO this isn't elegant at all!
	// its too fragile and prone to break.
})

jQuery("body").on("click", ".edit_question", function() {
	var url = $(this).attr("href");	
	var param = url.split('&');
	
	for ( i = 0; i < param.length; i++ )  {
	var val = param[i].split("=");
		if (val[0] == "q_id") {
			var q_id = decodeURIComponent(val[1]);
		}
	}	
	
	var jqxhr = jQuery.ajax( url )
		.done(function(msg) {
		
		if (jQuery("#question-" + q_id).length ) {
			//TODO: unsaved chagnes could be lost! Catch them!
			jQuery("#question-" + q_id).remove();
			jQuery(".ia").last().after(msg)
		} else {
			$(".ia").append(msg);
		}
	})
	
	.fail( function() {
		jQuery(".ia").after( "<div><strong>Failed to load question details.</strong></div>" );
	});
	
	$("#submit_questions").css("display", "block");
	
	return false;
});


jQuery("body").on( "click", "#submit_questions", function() {	
	var appears_at = 0;
	var mul_choice = [];
	var match_the_following = [];
	
	$(".question").each( function() {
		var q_id = "";
		if ( ! $(this).find(".q_title").val() ) {
			$(this).find(".q_title").focus();
			return;
		}
			
		if ( $(this).attr("id") ) {
			q_id = $(this).attr("id");			
		} else {
			q_id = "new";
		}
		
		var action = $(this).attr("delete");
		/* 
			Get the question ID, if empty, tag it as new.
			Get the question title
			Get the list of answers
			Get the right answers options			
		*/	
		
		if ( $(this).attr("q_mul_choice") == 1 ) {			
			var mkobj_mc = new Object();
						
			var ans_choice_mc = [];			
			var answers_mc = [];
			
			mkobj_mc.question_title = $(this).find(".q_title").val();
			
			$(this).find("textarea").each( function() {
				if ( $(this).val() ) {
					ans_choice_mc.push( $(this).val() );
					if ( $(this).next().is(":checked") ) {
						answers_mc.push(1);
					} else {
						answers_mc.push(0);
					}
				} else {
					if ( $(this).next().is(":checked") ) {
						alert("You should fill in an answer to select it as right answer!");
					}
				}
				
			});
		
			if ( jQuery.type(action) != "undefined" ) {
				mkobj_mc.delete_question = action;
			}
			
			mkobj_mc.q_identifier = q_id;
			mkobj_mc.answer_options = ans_choice_mc;
			mkobj_mc.right_or_wrong = answers_mc;
			
			if ( q_id == "new" ) {
				appears_at++;
				mkobj_mc.place_at = appears_at;
			} else {
				mkobj_mc.place_at = 0;
			}
			
			mul_choice.push(mkobj_mc);
			
		} else if ( $(this).attr("q_match_following") == 1 ) {
			var mkobj_mtf = new Object();
			var mtf_map = [];
			mkobj_mtf.question_title = $(this).find(".q_title").val();
			
			if ( $(this).attr("id") ) {
				q_id = $(this).attr("id");
			} else {
				q_id = "new";
			}
			
			if ( jQuery.type(action) != "undefined" ) {
				mkobj_mtf.delete_question = action;
			}
			
			$(this).find(".mapping").each(function( mapping_number ) {
				var mtf_matching_choices = [];
				//alert($(this).siblings().length);
				mtf_matching_choices.push( $(this).find(".left_column textarea").val() );
				mtf_matching_choices.push( $(this).find(".right_column textarea").val() );
				mtf_map.push( mtf_matching_choices );
				
			});
			
			if ( jQuery.type(action) != "undefined" ) {
				mkobj_mtf.delete_question = action;
			}
			
			mkobj_mtf.q_identifier = q_id;
			mkobj_mtf.mtf_mapping = mtf_map;
			mkobj_mtf.place_at = appears_at;
			
			if ( q_id == "new" ) {
				appears_at++;
				mkobj_mtf.place_at = appears_at;
			} else {
				mkobj_mtf.place_at = 0;
			}
			
			match_the_following.push( mkobj_mtf );
					
		} else {
			alert("Unrecognized question type!");
		}
		
	});
	
	var submit_this_object = new Object();
	submit_this_object.multiple_choice = mul_choice;
	submit_this_object.match_the_following = match_the_following;
	
	jQuery.ajax({
		url		:	"aq.php",
		data	:	jQuery.param( submit_this_object ),
		type	:	"POST",
		}).done( function( msg ) {
			$("#results").html("<div>" + msg + "</div>");
	});	
		
});


jQuery("body").on("click", ".del_mapping", function() {
	$(this).parent().parent().remove();	
	return false;
});

jQuery(".left_column .left_option").click(function() {
	var left_selected = 0;
	var right_selected = 0;
	var used_colors = new Array();
	jQuery(this).parent().parent().find(".left_option").each(function() {
		if ( $(this).css("background-color") != "transparent" && jQuery(this).css("background-color") != "rgb(0,0,0,0)" ) {
			left_selected++;
		}
	});

	jQuery(this).parent().parent().find(".right_option").each(function() {
		if ( $(this).css("background-color") != "transparent" && jQuery(this).css("background-color") != "rgb(0,0,0,0)" ) {
			right_selected++;
		}
	});

	

	
	if ( jQuery(this).css("background-color") == "transparent" || jQuery(this).css("background-color") == "rgb(0,0,0,0)" ) {	
		
		if ( left_selected == right_selected ) {
			$(this).parent().parent().find(".left_column .left_option").each(function() {		
				$(this).removeAttr("now_mapping");
				used_colors.push( $(this).css("background-color") );
			});
			$(this).css("backgroundColor", get_random_color(used_colors));
			$(this).attr("now_mapping", 1);
		}
	}
});


jQuery(".right_column .right_option").click(function() {
		
	if ( jQuery(this).css("background-color") == "transparent" || jQuery(this).css("background-color") == "rgb(0,0,0,0)" ) {
		var last_popped_color = jQuery(this).parent().parent().find("[now_mapping = '1']").css("background-color");
		//console.log(last_popped_color);
		
		$(this).parent().parent().find(".right_option").each(function() {
			if ( $(this).css("background-color") == last_popped_color ) {			
				$(this).css("background-color", "transparent");
			}
		});
		
		$(this).css("backgroundColor", last_popped_color);
	}
});

function get_random_color( used_colors ) {

	var colors = new Array("rgb(222, 184, 135)","rgb(0, 255, 255)", "rgb(47, 79, 79)", "rgb(240, 128, 128)", "rgb(119, 136, 153)", "rgb(0, 250, 154)", "rgb(245, 222, 179)","rgb(160, 180, 240)" );
	var last_popped_color;
	

	while ( true ) {
		last_popped_color = colors.pop(colors);
		if ( jQuery.inArray(last_popped_color, used_colors) == -1 ) {
			return last_popped_color;
		}
	}
}



























jQuery("#submit_test").click(function() {
	var submit_test = true;
	var submit_this_object = new Object();
	
	var mul_choice = [];
	var match_the_following = [];
	
	$(".question").each( function() {
		var q_title = $(this).find(".q_title").text();
		q_id = $(this).attr("id");

		if ( $(this).attr("q_type") == "multiple_choice" ) {		
			var mkobj_mc = new Object();
						
			var chosen_answers = [];			
						
			$(this).find(".mc_ans_grp").each( function() {
				if ( $(this).find(".mc_ans_chkbox").is(":checked") ) {
					chosen_answers.push( $(this).find(".mc_ans_text").text() );
				}
			});
			
			mkobj_mc.q_identifier = q_id;
			mkobj_mc.selected_answers = chosen_answers;
						
			mul_choice.push(mkobj_mc);
			
		} else if ( $(this).attr("q_type") == "match_the_following" ) {
			var mkobj_mtf = new Object();
			var left_options = new Array();
			var right_options = new Array();
			var mtf_matching_choices = [];
			
			q_id = $(this).attr("id");			
			var colors = new Array();	
			$(this).find(".left_option").each(function() {
				var found = false;
				//alert($(this).siblings().length);
				if ( jQuery(this).css("background-color") != "transparent" && jQuery(this).css("background-color") != "rgb(0,0,0,0)" ) {
						var color = $(this).css("background-color");
						left_options.push($(this).text());
						//console.log(color);
						$("#" + q_id).find(".right_option").each(function() {
							if ( $(this).css("background-color") == color ) {
								right_options.push($(this).text());
								found = true;
							}
						});
					
					if ( ! found ) {
						alert("You haven't mapped all the answers yet.");
						return;
					}
				}
			});
			
			if ( ( $(this).find(".left_option").length != left_options.length ) || ( $(this).find(".right_option").length != right_options.length ) ) {
				alert("You should map all");
				return;
			}
			mkobj_mtf.q_identifier = q_id;
			mkobj_mtf.left_opts = left_options;
			mkobj_mtf.right_opts = right_options;
			
			match_the_following.push(mkobj_mtf);
			//alert("Unrecognized question type!");
		}		
	});
	
	console.log(match_the_following);
	var submit_this_object = new Object();
	submit_this_object.multiple_choice = mul_choice;
	submit_this_object.match_following = match_the_following;
	
	
	var param = window.location.search;
	
	
	var val = param.split("&");
	var test_id;
	for ( i = 0; i < val.length; i++ )  {	
		if ( val[i].split("=")[0] == "t_id" ) {
			test_id = val[i].split("=")[1];
			break;
		}
	}
	console.log(test_id);
	submit_this_object.t_id = test_id;
	
	if ( submit_test ) {			
			$.ajax( {
				url		: 		"ajaxify.php?submit_test",
				type	: 		"POST",
				data	:		 submit_this_object,
				dataType:		"text",		
			}).done(function(response) {		
						jQuery(".results").html(response);
					});
			return false;				
	} else {
		alert("Looks like you want to wait for some more time before you submit your answers! Alright.");
	}
	
});


jQuery("body").on("click", ".delete_question", function() {
	var q_id = jQuery(this).attr("question");
	
	jQuery("#question-" + q_id).attr("delete", "y");	
	jQuery("#question-" + q_id).css("display", "none");
	
	//console.log(jQuery(".question").length);
	
});

